import type { TemplateTableRecord } from '@/api/Plan';
import { getStudyPlanTemplateList } from '@/api/Plan';
import CusDrawer from '@/components/CusDrawer';
import { Button } from 'antd';
import { isEmpty } from 'lodash-es';
import { forwardRef, useImperativeHandle, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { TemplateDrawerRef, TemplatePreviewDrawerProps } from './interface';
import TemplatePreviewDrawer from './TemplatePreviewDrawer';

const DRAWERWIDTH = 750;
const StudyPlanTemplateDrawer = forwardRef<TemplateDrawerRef, { entId: string }>((props, ref) => {
  const { entId } = props;
  const [open, setOpen] = useState(false);
  const [currPrevDetail, setCurrPrevDetail] = useState<TemplatePreviewDrawerProps['prevDetail']>(); //点击预览时保存
  const [tpOpen, setTpOpen] = useState(false);
  const navigator = useNavigate();

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
  }));

  const tempDrawerConfig = useMemo(
    () => ({
      width: DRAWERWIDTH,
      open,
      onClose: () => {
        setOpen(false);
      },
      destroyOnClose: true,
      title: '计划模板',
      bodyStyle: { background: 'transparent', padding: 0 },
      push: { distance: 180 },
    }),
    [open, entId],
  );

  const _useTemplateFn = (prevDetail: TemplatePreviewDrawerProps['prevDetail']) => {
    setTpOpen(false);
    setOpen(false);
    const prevDetailStr = JSON.stringify(prevDetail);
    navigator(
      //'100':固定时间，'200'：循环
      `/plannedManage/addStudyPlan?type=add&planType=${
        prevDetail.cycleType == 'fixed' ? '100' : '200'
      }&previewDetailStr=${prevDetailStr}`,
    );
  };

  // 使用计划模板
  const handleTpUse = () => {
    if (isEmpty(currPrevDetail)) return;
    _useTemplateFn(currPrevDetail);
  };

  const columns: YmColumnsType<TemplateTableRecord> = useMemo(
    () => [
      {
        title: '模板名称',
        dataIndex: 'name',
        key: 'name',
        width: 200,
      },
      {
        title: '是否收费',
        dataIndex: 'isCharge',
        key: 'isCharge',
        width: 80,
        render(value, record) {
          return record.isCharge == 1 ? '是' : '否';
        },
      },
      {
        title: '类型',
        dataIndex: 'cycleType',
        key: 'cycleType',
        width: 100,
        render: (text, record) => <span>{text === 'fixed' ? '固定学习' : `每${record.cycleDay}日一学`}</span>,
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 150,
        render: (text, record) => <span>{text ? text : record.creatTime}</span>,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        render: (text, record) => [
          <Button
            key="preview"
            type="text"
            size="small"
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation();
              const { guid, cycleType, cycleDay, name, learnMode, faceImg, isCharge } = record;
              setCurrPrevDetail({ guid, cycleType, cycleDay, name, learnMode, faceImg, isCharge });
              setTpOpen(true);
            }}
          >
            <span className="safe-edu_table_operation_text">预览</span>
          </Button>,
          <Button
            key="use"
            type="text"
            size="small"
            onClick={(e: React.MouseEvent) => {
              const { guid, cycleType, cycleDay, name, learnMode, faceImg, isCharge } = record;
              e.stopPropagation();
              _useTemplateFn({ guid, cycleType, cycleDay, name, learnMode, faceImg, isCharge });
            }}
          >
            <span className="safe-edu_table_operation_text">使用</span>
          </Button>,
        ],
      },
    ],
    [currPrevDetail?.guid],
  );

  return (
    <CusDrawer {...tempDrawerConfig}>
      <div style={{ height: '100%' }}>
        <YmTable<TemplateTableRecord, null>
          rowKey="guid"
          columns={columns}
          toolBar={false}
          request={async ({ page }, value = null) => {
            const result = await getStudyPlanTemplateList({ entId }, page?.pageIndex, page?.pageSize);
            return result;
          }}
          requestOptions={{
            defaultPageSize: 20,
          }}
        />

        {!isEmpty(currPrevDetail) && (
          <TemplatePreviewDrawer
            prevDetail={currPrevDetail}
            tpOpen={tpOpen}
            OnTpClose={() => {
              setTpOpen(false);
            }}
            onTpUse={handleTpUse}
          />
        )}
      </div>
    </CusDrawer>
  );
});

export default StudyPlanTemplateDrawer;
